package com.haixiaoke.saas.system.framework.web.service;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.CacheConstants;
import com.haixiaoke.saas.common.constant.Constants;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysUser;
import com.haixiaoke.saas.common.core.redis.RedisCache;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.exception.user.*;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.MessageUtils;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.common.utils.ip.IpUtils;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.manager.AsyncManager;
import com.haixiaoke.saas.system.framework.manager.factory.AsyncFactory;
import com.haixiaoke.saas.system.framework.security.context.AuthenticationContextHolder;
import com.haixiaoke.saas.system.service.ISysConfigService;
import com.haixiaoke.saas.system.service.ISysUserService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author haixiaoke
 */
@Component
@Slf4j
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IBizUserBusinessService iBizUserBusinessService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private WxMaService wxMaService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid, true);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "账号密码错误"));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 登录验证
     *
     * @param phoneNumber 用户手机号
     * @param password    密码
     * @param code        验证码
     * @param uuid        唯一标识
     * @return 结果
     */
    public LoginUser enterpriseLogin(String phoneNumber, String password, String code, String uuid, String platform, String tenantId) {
        // 验证码校验
        // validateCaptcha(phoneNumber, code, uuid, true);
        // 登录前置校验
        loginPreCheck(phoneNumber, password);
        // 用户验证
       /* Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phoneNumber, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);


        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();*/
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = userDetailsService.enterpriseLogin(phoneNumber, password, tenantId);
        recordLoginInfo(loginUser.getUserId());
        bizRecordLoginInfo(loginUser.getUserId());
        loginUser.setPlatform(platform);
        loginUser.setTenantId(tenantId);
        // 生成token
        return loginUser;
    }

    public LoginUser manageLogin(String username, String password, String code, String uuid, String platform) {
        // 验证码校验
        validateCaptcha(username, code, uuid, true);
        // 登录前置校验
        loginPreCheck(username, password);

//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//        AuthenticationContextHolder.setContext(authenticationToken);
        // 用户验证
        /*Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }*/
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = userDetailsService.manageLogin(username, password);
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return loginUser;
    }


    /**
     * 验证码登录
     *
     * @return 登录结果
     */
    public LoginUser captchaLogin(String mobile, String code, String tenantId) {
        // 验证码校验
        validateMobileCaptcha(mobile, code, true);


        LoginUser loginUser = userDetailsService.captchaLogin(mobile,tenantId);
        bizRecordLoginInfo(loginUser.getUserId());
        return loginUser;
    }

    public void validateMobileCaptcha(String mobile, String code, Boolean delFlag) {
        String verifyKey = CacheConstants.SMS_CAPTCHA_KEY + mobile;
        String captcha = redisCache.getCacheObject(verifyKey);
        if (delFlag) {
            redisCache.deleteObject(verifyKey);
        }
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_FAIL, "验证码不存在"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_FAIL, MessageUtils.message("验证码错误")));
            throw new CaptchaException();
        }
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @param delFlag  是否删除换成标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid, Boolean delFlag) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (delFlag) {
                redisCache.deleteObject(verifyKey);
            }
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "登录失败"));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("验证码错误")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public void bizRecordLoginInfo(Long userId) {
        BizUserBusiness bizUser = new BizUserBusiness();
        bizUser.setUserId(userId);
        bizUser.setLoginIp(IpUtils.getIpAddr());
        bizUser.setLoginDate(DateUtils.getNowDate());
        iBizUserBusinessService.updateUserBusState(bizUser);
    }

    public AjaxResult getPhoneNumber(LoginBody loginBody) {
        String code = loginBody.getCode();
        String encryptedData = loginBody.getEncryptedData();
        String iv = loginBody.getIv();

        WxMaJscode2SessionResult session = null;
        try {
            session = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            throw new ServiceException("获取信息异常：" + e.getLocalizedMessage());
        }
        String openid = session.getOpenid();

        String sessionKey = session.getSessionKey();
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        if (StrUtil.isBlank(phoneNumber) || StrUtil.isBlank(openid)) {
            throw new ServiceException("获取信息失败");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("phonenumber", phoneNumber);
        ajax.put("openId", openid);
        return ajax;
    }
}
